package com.siyoumi.mybatispuls;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;

import java.util.*;

public class EntityBase<T> {
    /**
     * 前缀
     *
     * @return String
     */
    public String prefix() {
        return "";
    }

    /**
     * 表名
     */
    static public String table() {
        return "";
    }


    /**
     * 主键
     *
     * @return String
     */
    @JsonIgnore
    @JSONField(serialize = false)
    public String getKey() {
        Object v = getAttributeVal(getEntityKeyName("id"), null);
        if (v == null) {
            return null;
        }
        return v + "";
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public Object getKeyObj() {
        return getAttributeVal(getEntityKeyName("id"));
    }

    /**
     * X
     *
     * @return String
     */
    @JsonIgnore
    @JSONField(serialize = false)
    public String getX() {
        return getAttributeVal(getEntityKeyName("x_id"));
    }

    public void setAutoID(Boolean addPrefix) {
        String val = XApp.getStrID(); //雪花算法
        if (addPrefix) {
            //val = String.format("%s%s", prefix().replace("_", "-"), val);
            String prefix = prefix().replace("_", "");
            String PREFIX = prefix.toUpperCase();
            if (prefix.length() > 4) {
                PREFIX = prefix.substring(0, 4).toUpperCase();
            }
            val = String.format("%s%s", PREFIX, val);
        }
        setAttributeVal(getEntityKeyName("id"), val);
    }

    public void setAutoID() {
        setAutoID(true);
    }

    public String getEntityKeyName(String key) {
        return String.format("%s%s", prefix(), key);
    }

    public <TA> TA getAttributeVal(String key, TA def) {
        Object val = XBean.getAttributeVal(this, key);
        if (val == null) {
            return def;
        }

        return (TA) val;
    }

    public <TA> TA getAttributeVal(String key) {
        return getAttributeVal(key, null);
    }

    public void setAttributeVal(String key, Object val) {
        XBean.setAttributeVal(this, key, val);
    }

    public Map<String, Object> toMap() {
        List<String> ignoreField = new ArrayList<>();
        ignoreField.add("key");
        ignoreField.add("keyObj");
        ignoreField.add("class");
        ignoreField.add("x");

        return XBean.toMap(this, ignoreField);
    }
}
